import Vue from 'vue'
import Vuex from 'vuex'
import setting from './modules/setting'
import route from './modules/route'
import {asyncRouterMap, constantRouterMap} from '../router/lazy'
import {auth} from '../utils/auth'
import {logout} from '../http/request'
import {getUserInfo} from "../http/request";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    loading: false,
    routes: [],
    addRoutes: [],
    user: null,
    install: false
  },
  modules: {
    setting,
    route,
  },
  getters: {
    user: state => {
      if (!state.user) {
        let json = window.localStorage.getItem("user");
        if (json)
          state.user = JSON.parse(json);
      }
      return state.user
    }
  },
  mutations: {
    setUser(state, user) {
      state.user = user;
      window.localStorage.setItem("user", JSON.stringify(user));
    },
    setRoutes(state, routes) {
      state.addRoutes = routes;
      state.routes = constantRouterMap.concat(routes);
      console.log(state.routes);
    },
    openLoading(state) {
      state.loading = true
    },
    closeLoading(state) {
      state.loading = false
    },
    installRouter(state) {
      state.install = true
    },
    logout(state) {
      console.log("logout");
      logout(auth.getToken());
      state.user = null;
      state.install = false;
      window.localStorage.removeItem("user");
      auth.removeToken();
    }
  },
  actions: {
    generateRoutes({commit}) {
      return getUserInfo().then((res) => {
        auth.setRoles(res.data.roles);
        let accessedRouters = auth.filterRouter(asyncRouterMap);
        commit("setUser", res.data);
        commit('setRoutes', accessedRouters);
      });
    }
  }
})
